<template>
  <div class="">
    <el-row v-if="showRole" :gutter="10" class="right_box">
      <el-col v-if="showRole" :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleNewOrg"
        >新增机构</el-button>
      </el-col>
      <el-col v-if="showRole" :span="1.5">
        <el-button
          type=""
          plain
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
                <el-button
                    type=""
                    plain
                    size="mini"
                    @click="handledownload">下载架构图</el-button>
            </el-col> -->
      <el-col :span="1.5">
        <router-link :to="{ path: '/department/historyArc'}">
          <el-button type="primary" plain size="mini">历史架构图</el-button>
        </router-link>
        <!-- <el-button
                    type=""
                    plain
                    size="mini"
                   >历史架构图</el-button> -->
      </el-col>

    </el-row>
    <el-row>
      <el-col :span="24"><div id="chartBox" ref="chart" style="width:100%;height:calc(100vh - 84px);" /></el-col>
    </el-row>
    <!-- 用户导入对话框 -->
    <el-dialog :title="uploads.title" :visible.sync="uploads.open" width="500px" append-to-body>
      <div class="tep1">
        <el-row>
          <el-col :span="24">第1步</el-col>
          <el-col :span="24"><el-link
            :underline="false"
            style="font-size:12px;vertical-align: baseline;margin-top: 10px;"
            @click="importTemplate"
          >点击下载空的<span style="color:blue">表格模板</span></el-link></el-col>
        </el-row>
      </div>
      <div class="tep1">
        <span>第2步</span>
        <!-- :disabled="uploads.isUploading" -->
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          class="upload-demo"
          :action="fileUploadUrl"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload" />

          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div slot="tip" class="el-upload__tip text-center">
            <span>(仅允许导入xls、xlsx格式文件。)</span>
          </div>
        </el-upload>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="uploads.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import * as echarts from 'echarts'
import {
  listMechanism,
  delDepartment
} from '@/api/hr/department'
import { fileUploadUrl } from '@/api/hr/upload'
export default {
  name: 'TreeChart',
  data() {
    return {
      showRole: false,
      data: [], // 树结构数据
      DataList: [],
      myChart: null,
      option: {}, // echarts配置
      employeeRole: [], // 角色
      echartData: [],
      fileList: [],
      fileUploadUrl, // 文件上传路径
      // 用户导入参数
      uploads: {
        open: false,
        title: '',
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0
      }
    }
  },
  created() {
    this.employeeRole = JSON.parse(
      localStorage.getItem('userinfo')
    ).employeeRole

    if (this.employeeRole.indexOf('1') !== -1 || this.employeeRole.indexOf('3') !== -1 || this.employeeRole.indexOf('6') !== -1) {
      this.showRole = true
    }
    // 获取数据
    this.getList()
  },
  mounted() {
    window.handleAdd = this.handleAdd
    window.handleEdit = this.handleEdit
    window.handleDelete = this.handleDelete
  },
  beforeDestroy() {
    if (this.myChart) {
      this.myChart.dispose()
    }
  },
  methods: {
    getList() {
      listMechanism({}).then(res => {
        // 转换数据
        this.data = this.eachReplaceKey(res.data)
        this.drawChart()
      })
    },
    // 处理数据
    eachReplaceKey(data) {
      const item = []
      data.map((list) => {
        const newData = {}
        newData.id = list.id
        newData.name = list.institutionName //
        newData.children = list.dson
        newData.value = list.peopleNumber // 总人数
        newData.institutionGrade = list.institutionGrade // 机构等级
        newData.institutionNumber = list.institutionNumber // 机构编码"
        newData.administrationRankValue = list.administrationRankValue // 行政级另"
        newData.institutionFather = list.institutionFatherName // 上级机构"
        newData.xzPeople = list.xzPeople // 行政负责"
        newData.dwPeople = list.dwPeople // 党务负责"
        newData.institutionPlace = list.institutionPlace // 办必地址"
        newData.phone = list.phone // 电话号码"
        newData.remark = list.remark // 职责描述"
        newData.dwphone = list.dwphone // 党务负责人号码
        newData.classification = list.classification // 行政级别
        newData.settingNumber = list.settingNumber // 在编人数"
        newData.maxNumber = list.maxNumber // 在岗人数
        newData.organizationNum = list.organizationNum // 组织编号
        if (list.dson != null) {
          newData.children = this.eachReplaceKey(list.dson)
        }
        item.push(newData)
      })
      return item
    },
    drawChart() {
      // 初始化图表
      this.myChart = echarts.init(this.$refs.chart)
      this.myChart.clear() // 清除图表缓存
      // this.myChart.showLoading({
      //     text: '数据加载中...',
      //     color: '#c23531',
      //     textColor: '#000',
      //     maskColor: 'rgba(255, 255, 255, 0.8)',
      //     zlevel: 0
      // });
      // var echartNowData = [] // 当前鼠标所在的节点数据
      // 指定图表的配置项和数据
      this.option = {
        backgroundColor: 'rgba(26, 107, 232, 0.047058823529411764)',
        calculable: false,
        tooltip: {
          trigger: 'item', // item
          triggerOn: 'mousemove', // click  mousemove
          backgroundColor: 'unset',
          position: 'right', //
          renderMode: 'html',
          enterable: true,
          padding: 0,
          // left:-18,
          textStyle: {
            color: 'white' // 设置 tooltip
          },
          formatter: function(params) {
            // echartNowData = params.data
            const nameData = {
              name: ''
            }
            var hasChildren
            if (params.data.children != null) {
              if (params.data.children.length > 0) {
                hasChildren = true
              }
            } else {
              hasChildren = false
            }

            if (params.data.classification === 24) nameData.name = '机构名称'
            if (params.data.classification === 25) nameData.name = '部门名称'
            if (params.data.classification === 26) nameData.name = '科室名称'

            const html = ` <div style="position: absolute;left: -20px;bottom: 190px;float: left;display:flex;justify-content: space-between; flex-direction: column;align-items:flex-end">
                    <span onclick="handleAdd('${params.data.id}')" style="pointer-events: auto;display:block;width:29px;height:29px;border-radius: 50%;margin-bottom: 5px;background: #1AA094;text-align:center;font-size: 18px;padding-top: 5px;" class="el-icon-plus"></span>
                    <span onclick="handleEdit('${params.data.id}')" style="pointer-events: auto;display:block;width:29px;height:29px;border-radius: 50%;margin-bottom: 5px;background: #1AA094;text-align:center;font-size: 18px;padding-top: 5px;" class="el-icon-edit-outline"></span>
                    <span onclick="handleDelete('${params.data.id}','${hasChildren}')" style="pointer-events: auto;display:block;width:29px;height:29px;border-radius: 50%;background: #1AA094;text-align:center;font-size: 18px;padding-top: 5px;" class="el-icon-delete"></span>
                    </div>
                    <div style="background:white;border-radius: 7px;color: #666; display: flex;justify-content: space-between; padding:26px;">
                        <div>
                        <p>编码：</p>
                        <p>${nameData.name}：</p>
                        <p>行政级别：</p>
                        <p>机构等级：</p>
                        <p>上级机构：</p>
                        <p>行政负责人：</p>
                        <p>行政负责人号码：</p>
                        <p>党务负责人：</p>
                         <p>党务负责人号码：</p>
                        <p>办公地址：</p>
                        <p>定编人数: </p>
                        <p>在编人数：</p>
                        <p>在岗人数：</p>
                        <p>组织描述：</p>
                        </div>
                        <div style="text-align: right">
                        <p>${params.data.institutionNumber || '-'}</p>
                        <p>${params.data.name || '-'}</p>
                        <p>${params.data.administrationRank || '-'}</p>
                        <p>${params.data.institutionGrade || '-'}级</p>
                        <p>${params.data.institutionFather || '-'}</p>
                        <p>${params.data.xzPeople || '-'}</p>
                        <p>${params.data.phone || '-'}</p>
                        <p>${params.data.dwPeople || '-'}</p>
                         <p>${params.data.dwphone || '-'}</p>
                        <p>${params.data.institutionPlace || '-'}</p>
                        <p>${params.data.maxNumber || '-'}人</p>
                        <p>${params.data.settingNumber || '-'}人</p>
                        <p>${params.data.maxNumber || '-'}人</p>
                         <p>${params.data.remark || '-'}</p>
                        </div>
                    </div>`
            return html
          }
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              show: true
            }
            // saveAsImage:{
            //   show:true
            // },

          }
        },
        series: [
          {
            name: '树图',
            type: 'tree',
            orient: 'vertical', // vertical horizontal
            rootLocation: { x: '50%', y: '15%' }, // 根节点位置  {x: 'center',y: 10}
            hoverAnimation: false,
            nodePadding: 8,
            layerPadding: 30,
            // symbol: 'rectangle',
            borderColor: 'black',
            symbolSize: [160, 100],
            symbol: 'rect',
            symbolKeepAspect: true,
            edgeShape: 'polyline',
            roam: true,
            initialTreeDepth: -1,
            left: '-360%',
            width: 12500,
            expandAndCollapse: false,

            itemStyle: {
              normal: {
                color: 'rgba(255, 255, 255, 1)', // 节点背景色
                'borderWidth': 1,
                'borderColor': '#b2d8d4',
                label: {
                  show: true,
                  position: 'inside',
                  backgroundColor: 'rgba(255, 255, 255, 1)',
                  lineHeight: 20,
                  textStyle: {
                    color: '#696969',
                    fontSize: 14
                    // fontWeight:  'bolder'
                  },
                  formatter: function(params) {
                    return params.data.name + '\n在编人数:' + params.data.settingNumber + '\n在岗人数:' + params.data.maxNumber
                  }
                },
                lineStyle: {
                  color: '#7fcac3',
                  width: 1
                }
              },
              emphasis: {
                // 鼠标悬停时的样式
                borderColor: '#42b983',
                borderWidth: '2'
              }

            },

            data: this.data
          }
        ]
      }

      // 使用刚指定的配置项和数据显示图表。
      this.myChart.setOption(this.option)
      // this.myChart.hideLoading()
    },

    handleNewOrg() {
      this.$router.push({ path: '/department/orgAdd', query: { Id: undefined, Title: '新增组织' }})
    },

    // 节点新增
    handleAdd(id) {
      this.$router.push({ path: '/department/orgAdd', query: { Id: undefined, Title: '新增组织', institutionFather: id }})
    },
    // 编辑
    handleEdit(id) {
      this.$router.push({ path: '/department/orgedit', query: { Id: id, Title: '编辑组织' }})
    },
    // 删除
    handleDelete(id, isTure) {
      // const ids =row.id;
      if (isTure != 'true') {
        this.$modal
          .confirm('是否确认删除此组织机构数据项？')
          .then(() => {
            return delDepartment({ ids: id })
          })
          .then(() => {
            this.$modal.msgSuccess('删除成功')
            this.getList()
          })
          .catch(() => {})
          .finally(() => {
          })
      } else {
        this.$message({
          message: '该组织机构存在下级机构或者人员，请先迁移下级机构或人员',
          type: 'warning'
        })
      }
    },

    /** 导出文件 */
    handleExport() {
      console.log('点击导出了')
      this.download(
        '/sc/department/getExcel',
        {},
        `组织机构_${new Date().getTime()}.xls`
      )
    },
    //  导入
    handleImport() {
      this.uploads.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        '/sc/department/downExcel',
        {
          // ...this.queryParams
        },
        `mechanism_${new Date().getTime()}.xls`
      )
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.uploads.isUploading = true
    },
    // 文件上传(导入成功后的回调)
    handleFileSuccess(response, file, fileList) {
      if (response.code == 1) {
        // Message({ message: '上传成功，正在解析' })
        const rel_url = response.data[0].relative_url
        // 上传成功后,向导入数据的接口发送一个服务器文件地址
        // uploadExcel(rel_url)
        //   .then((res) => {
        //     // 解析excel成功,重新获取列表
        //     this.getList()
        //   })
        //   .finally(() => {
        //     this.fileList = []
        //   })
      } else {
        // Message({ message: response.msg, type: 'error' })
      }
    },
    // 提交导入文件
    submitFileForm() {
      this.$refs.upload.submit()
    },

    // 下载图片
    downloadImage1() {
      // 获取图表的 Base64 URL
      var base64URL = this.myChart.getDataURL({
        type: 'jpeg', // 或者 'jpeg'
        pixelRatio: 2, // 导出的图片分辨率比例
        backgroundColor: 'rgba(26, 107, 232, 0.047058823529411764)' // 导出的图片背景色，默认使用 option 里的 backgroundColor
      })

      // 创建一个 Blob 对象，用于保存图片的二进制数据
      var blob = this.dataURLtoBlob(base64URL)

      // 创建一个隐藏的 a 标签用于下载
      var a = document.createElement('a')
      a.href = URL.createObjectURL(blob)
      a.download = 'echart.png' // 设置下载文件的名称
      a.style.display = 'none'

      // 触发 a 标签的 click 事件开始下载
      document.body.appendChild(a)
      a.click()

      // 之后可以移除 a 标签
      document.body.removeChild(a)
    },

    // 将 Base64 URL 转换为 Blob 对象
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(','); var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },

    // 下载图片
    downloadImage() {
      this.downloadCanvasAsImage(null, 'chartBox', 'zzjg.png')
    },
    downloadCanvasAsImage(link, canvasId, filename) {
      var chartBox = document.getElementById('chartBox')
      if (chartBox) {
        var firstDiv = chartBox.children[0]
        if (firstDiv && firstDiv.tagName.toLowerCase() === 'div') {
          var canvas = firstDiv.children[0]
          if (canvas && canvas.tagName.toLowerCase() === 'canvas') {
            // 对canvas进行操作
            console.log(canvas)
            var imageUrl = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream')
            var linkElement = document.createElement('a')
            linkElement.setAttribute('href', imageUrl)
            linkElement.setAttribute('download', filename)
            linkElement.click()
            //   var img = document.createElement('img');
            //     img.src = imageUrl;
            //     img.width=canvas.width;
            //     img.height=canvas.height;

            //     // 新标签页中显示图片
            //     var newTab = window.open('', '_blank');
            //     newTab.document.write('<img src="' + img.src + '" alt="Canvas Image" />');
          }
        }
      }
    }

  }

}
</script>

<style lang="scss" scoped>
/* 添加一些样式 */
    .right_box{
        float: right;
        margin-bottom: 20px;
        position: relative;
        z-index: 1;
    }
    .tep1{
      box-sizing: border-box;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      margin-bottom: 30px;
      padding: 10px;
    }
    ::v-deep .upload-demo{
      width: 100%;
      .el-upload-dragger{
        width:400px;
        border:0 !important;
      }
      .el-upload__tip{
        margin: 0 0 20px 0!important;
        text-align: center;
      }
    }
</style>
